package IO2;

import java.io.*;

/**
 * @description: IO_image_copy
 * 字节流  （文件都能转成字节数组）
 * 利用字节数组拷贝图片
 * 1.图片文件转字节数组
 * 2.字节数组转图片文件
 * @date: 2019/12/17 14:15
 * @author: Vicuna
 */


public class IO_image_copy {
    public static void main(String[] args) {
        String path = "src/img.jpg";
        byte a[] = ImageToByteArray(path);
        System.out.println(a.length);
        ByteArrayToImage(a, "src/p_copy.jpg");
    }

    /*
    1.图片到程序        FileInpStream
    2.程序到字节数组    ByteArrayOutputStream
    3.函数返回类型为 字节数组
     */
    public static byte[] ImageToByteArray(String filepath) {
        File f = new File(filepath);
        byte dest[] = null;
        InputStream is = null;
        ByteArrayOutputStream os = null;
        try {
            is = new FileInputStream(f);
            os = new ByteArrayOutputStream();
            //3.读取，写入操作
            byte hc[] = new byte[1024 * 100];       //缓冲容器
            int len = -1;                           //接收长度；
            while ((len = is.read(hc)) != -1) {
                os.write(hc, 0, len);            //写出到字节数组中
            }
            os.flush();
            dest = os.toByteArray();
            return dest;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /*
    1.字节数组到程序   ByteArrayInputStream
    2.程序到图片文件   FileOutputStream
     */
    public static void ByteArrayToImage(byte bt[], String filepath) {
        //1.创建源
        File f=new File(filepath);
        //2.选择流
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new ByteArrayInputStream(bt);
            os = new FileOutputStream(f, false);        //操作文件 f
            //3.操作
            byte hc[]=new byte[3];      //缓冲容器
            int len=-1;                 //接收长度；
            while ((len=is.read(hc))!=-1)
            {
                os.write(hc,0,len);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
